# -*- coding: utf-8 -*-
import logging

from selenium.common.exceptions import NoSuchElementException, TimeoutException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

from pages.base_page import BasePage
from objectsmap.page_locators import Search
from pages_exceptions.pages_exceptions import SearchException


class SearchPage(BasePage):
    TITLE = 'Online Backup & disaster recovery for serious scale IASO'
    LOCATION = 'https://www.iaso.com/kb/'

    def __init__(self, driver):
        super(SearchPage, self).__init__(driver, SearchPage.LOCATION)

    def is_right_location(self):
        super(SearchPage, self).is_right_location(SearchPage.TITLE)

    def search(self, search_parameters):
        try:
            self._driver.find_element(*Search.IN_QUERY).send_keys(search_parameters['request'])
            self._driver.find_element(*Search.BTN_SEARCH).click()
            WebDriverWait(self._driver, 10).until(EC.presence_of_all_elements_located
                                                  ((Search.SEARCH_RESULTS[0], Search.SEARCH_RESULTS[1])))
            logging.info('searching success')
        except (TimeoutException, NoSuchElementException) as e:
            raise SearchException('searching failed')


class SearchResultsPage(BasePage):

    def __init__(self, driver):
        super(SearchResultsPage, self).__init__(driver, '')
        self.search_results = self._driver.find_elements(*Search.SEARCH_RESULTS)

    def results_count(self):
        return len(self.search_results)

    def click_element(self, number):
        element = self.search_results[number-1]
        element.find_element(*Search.FIRST_ELEMENT).click()

    def article_title(self):
        title = self._driver.find_element(*Search.ARTICLE_TITLE)
        return title.text
